package com.bumptech.glide.load.model;

import com.bumptech.glide.load.Options;
import com.bumptech.glide.util.LogUtil;
import ohos.utils.net.Uri;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import ohos.app.Context;
import java.io.InputStream;

/**
 * A model loader for handling openharmony resource files. Model must be an openharmony resource id in the
 * package of the given context.
 *
 * @param <Data> The type of data that will be loaded for the given openharmony resource.
 */
public class ResourceLoader<Data> implements ModelLoader<Integer, Data> {
  private static final String TAG = "ResourceLoader";
  private final ModelLoader<Uri, Data> uriLoader;
  private final Context context;

  // Public API.
  @SuppressWarnings("WeakerAccess")
  public ResourceLoader(
      Context context, ModelLoader<Uri, Data> uriLoader) {
    this.context = context;
    this.uriLoader = uriLoader;
  }

  @Override
  public LoadData<Data> buildLoadData(
      @NotNull Integer model, int width, int height, @NotNull Options options) {
    Uri uri = getResourceUri(model);
    return uri == null ? null : uriLoader.buildLoadData(uri, width, height, options);
  }

  @Nullable
  private Uri getResourceUri(Integer model) {
    try { // model is just int and openharmony has different way to handle and create inputstream
      return Uri.parse(Integer.toString(model));
    } catch (Exception e) {
      if (LogUtil.isLoggable(TAG, LogUtil.WARN)) {
        LogUtil.warn(TAG, "Received invalid resource id: " + model);
      }
      return null;
    }
  }

  @Override
  public boolean handles(@NotNull Integer model) {
    // TODO: check that this is in fact a resource id.
    return true;
  }

  /** Factory for loading {@link InputStream}s from openharmony resource ids. */
  public static class StreamFactory implements ModelLoaderFactory<Integer, InputStream> {

    private final Context context;

    public StreamFactory(Context context) {
      this.context = context;
    }

    @NotNull
    @Override
    public ModelLoader<Integer, InputStream> build(MultiModelLoaderFactory multiFactory) {
      return new ResourceLoader<>(
          context, multiFactory.build(Uri.class, InputStream.class));
    }

    @Override
    public void teardown() {
      // Do nothing.
    }
  }

  /** Factory for loading resource {@link Uri}s from openharmony resource ids. */
  public static class UriFactory implements ModelLoaderFactory<Integer, Uri> {

    private final Context context;

    public UriFactory(Context context) {
      this.context = context;
    }

    @NotNull
    @Override
    public ModelLoader<Integer, Uri> build(MultiModelLoaderFactory multiFactory) {
      return new ResourceLoader<>(context, UnitModelLoader.<Uri>getInstance());
    }

    @Override
    public void teardown() {
      // Do nothing.
    }
  }
}
